﻿using Asxsyd92Core.Utils.Provider;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace Asxsyd92Core.Utils
{
   public class HttpHelper
    {/// <summary>
     /// 异步请求post（键值对形式,可等待的）
     /// </summary>
     /// <param name="uri">网络基址("http://localhost:59315")</param>
     /// <param name="url">网络的地址("/api/UMeng")</param>
     /// <param name="formData">键值对List<KeyValuePair<string, string>> formData = new List<KeyValuePair<string, string>>();formData.Add(new KeyValuePair<string, string>("userid", "29122"));formData.Add(new KeyValuePair<string, string>("umengids", "29122"));</param>
     /// <param name="charset">编码格式</param>
     /// <param name="mediaType">头媒体类型</param>
     /// <returns></returns>
        public static async Task<string> HttpPostAsync(string uri, string url, List<KeyValuePair<string, string>> formData = null, string charset = "UTF-8", string mediaType = "application/x-www-form-urlencoded")
        {

            string tokenUri = url;
            var client = new HttpClient();
            client.BaseAddress = new Uri(uri);
            HttpContent content = new FormUrlEncodedContent(formData);
            content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
            content.Headers.ContentType.CharSet = charset;
            for (int i = 0; i < formData.Count; i++)
            {
                content.Headers.Add(formData[i].Key, formData[i].Value);
            }

            HttpResponseMessage resp = await client.PostAsync(tokenUri, content);
            resp.EnsureSuccessStatusCode();
            string token = await resp.Content.ReadAsStringAsync();
            return token;
        }
        /// <summary>
        /// 同步请求post（键值对形式）
        /// </summary>
        /// <param name="uri">网络基址("http://localhost:59315")</param>
        /// <param name="url">网络的地址("/api/UMeng")</param>
        /// <param name="formData">键值对List<KeyValuePair<string, string>> formData = new List<KeyValuePair<string, string>>();formData.Add(new KeyValuePair<string, string>("userid", "29122"));formData.Add(new KeyValuePair<string, string>("umengids", "29122"));</param>
        /// <param name="charset">编码格式</param>
        /// <param name="mediaType">头媒体类型</param>
        /// <returns></returns>
        public static string HttpPost(string uri, string url, List<KeyValuePair<string, string>> formData = null, string charset = "UTF-8", string mediaType = "application/x-www-form-urlencoded")
        {
            string tokenUri = url;
            var client = new HttpClient();
            client.BaseAddress = new Uri(uri);
            HttpContent content = new FormUrlEncodedContent(formData);
            content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
            content.Headers.ContentType.CharSet = charset;
            for (int i = 0; i < formData.Count; i++)
            {
                content.Headers.Add(formData[i].Key, formData[i].Value);
            }

            var res = client.PostAsync(tokenUri, content);
            res.Wait();
            HttpResponseMessage resp = res.Result;

            var res2 = resp.Content.ReadAsStringAsync();
            res2.Wait();

            string token = res2.Result;
            return token;
        }
        /// <summary>
        /// 异步请求get(UTF-8)
        /// </summary>
        /// <param name="url">链接地址</param>    
        /// <param name="formData">写在header中的内容</param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(string url, List<KeyValuePair<string, string>> formData = null)
        {
            HttpClient httpClient = new HttpClient();
            HttpContent content = new FormUrlEncodedContent(formData);
            if (formData != null)
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                content.Headers.ContentType.CharSet = "UTF-8";
                for (int i = 0; i < formData.Count; i++)
                {
                    content.Headers.Add(formData[i].Key, formData[i].Value);
                }
            }
            var request = new HttpRequestMessage()
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get,
            };
            for (int i = 0; i < formData.Count; i++)
            {
                request.Headers.Add(formData[i].Key, formData[i].Value);
            }
            var resp = await httpClient.SendAsync(request);
            resp.EnsureSuccessStatusCode();
            string token = await resp.Content.ReadAsStringAsync();

            return token;
        }
        /// <summary>
        /// 同步get请求
        /// </summary>
        /// <param name="url">链接地址</param>    
        /// <param name="formData">写在header中的键值对</param>
        /// <returns></returns>
        public static string HttpGet(string url, List<KeyValuePair<string, string>> formData = null)
        {
            HttpClient httpClient = new HttpClient();
      
            if (formData != null)
            {
                HttpContent content = new FormUrlEncodedContent(formData);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                content.Headers.ContentType.CharSet = "UTF-8";
                for (int i = 0; i < formData.Count; i++)
                {
                    content.Headers.Add(formData[i].Key, formData[i].Value);
                }
            }
            var request = new HttpRequestMessage()
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get,
            };
            //for (int i = 0; i < formData.Count; i++)
            //{
            //    request.Headers.Add(formData[i].Key, formData[i].Value);
            //}
            var res = httpClient.SendAsync(request);
            res.Wait();
            var resp = res.Result;
            Task<string> temp = resp.Content.ReadAsStringAsync();
            temp.Wait();
            return temp.Result;
        }

        /// <summary>
        /// 百度推送更新
        /// </summary>
        /// <param name="urls"></param>
        /// <returns></returns>
        public static string BaiduPostUpdateUrl(string formUrl ,string[] urls)
        {
            try
            {

                string formData = "";

                foreach (string url in urls)
                {
                    formData += url + "\r";
                }

                byte[] postData = System.Text.Encoding.UTF8.GetBytes(formData);

                // 设置提交的相关参数
                System.Net.HttpWebRequest request = System.Net.WebRequest.Create(formUrl) as System.Net.HttpWebRequest;
                System.Text.Encoding myEncoding = System.Text.Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = "text/plain";
                request.UserAgent = "curl/7.12.1";
                request.ContentLength = postData.Length;

                // 提交请求数据
                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();

                System.Net.HttpWebResponse response;
                System.IO.Stream responseStream;
                System.IO.StreamReader reader;
                string srcString;
                response = request.GetResponse() as System.Net.HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.GetEncoding("UTF-8"));
                srcString = reader.ReadToEnd();
                string result = srcString;   //返回值赋值
                reader.Close();

                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        public static bool SendEmail(string mailTo, string mailSubject, string mailContent,string vip="Vip提醒")
        {
            //设置发送方的邮件信息,使用最常见的qq邮箱
            string smtpServer = AppSetting.GetConfig("smtpServer") ;         //SMTP服务器
            string mailFrom = AppSetting.GetConfig("mailFrom");      //登陆用户名
            string SMTPPassword = AppSetting.GetConfig("SMTPPassword");  //SMTP授权码，这里会有人误解为邮箱的密码，其实是授权码，具体看下面获取授权码操作

            //邮件服务设置
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;  //邮件发送方式
            smtpClient.Host = smtpServer;                            //SMTP服务器
            smtpClient.Port = 587;                                   //qq邮箱SMTP发送端口，可以不填           
            smtpClient.EnableSsl = true;                             //qq邮箱SMTP SSL加密，可以不填 
            smtpClient.Credentials = new System.Net.NetworkCredential(mailFrom, SMTPPassword); //用户名和密码

            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;
            string senderDisplayName = "爱上歆随懿恫|asxsyd92.com|软件开发|net core";//这个配置的是发件人的要显示在邮件的名称   
            string recipientsDisplayName = vip;//这个配置的是收件人的要显示在邮件的名称   

            MailAddress mailfrom = new MailAddress(mailFrom, senderDisplayName, encoding);//发件人邮箱地址，名称，编码UTF8 
            MailAddress mailto = new MailAddress(mailTo, recipientsDisplayName, encoding);//收件人邮箱地址，名称，编码UTF8   
                                                                                          //创建mailMessage对象   
            System.Net.Mail.MailMessage message = new MailMessage(mailfrom, mailto);
            message.Subject = mailSubject;
            //正文默认格式为html   
            message.Body = mailContent;
            message.IsBodyHtml = true;
            message.BodyEncoding = encoding;
            message.SubjectEncoding = encoding;
            message.HeadersEncoding = encoding;

                            //优先级，可不填
  
            try
            {
                smtpClient.Send(message);         //发送邮件
                return true;
            }
            catch (SmtpException e)
            {
                return false;
            }
        }
    }
}
